#import os
#import tempfile
import re
#from subprocess import check_call, call

######## Execution contexts - use with the 'with' statement ##############

from forest.registry import register_tool
from forest.tool import Tool

from forest.tools.system.execute import poll

@register_tool('image.mkisofs')
def mkisofs(dest = "", bootloader = "", label = "", bootcat = ""):
    Tool.SIGNAL_TOOL_START(mkisofs, message="Creating iso filesystem...")

    for stderr, line in poll(['mkisofs', '-D', '-r', '-V', label, '-cache-inodes', '-J', '-l', '-b', bootloader, '-c', bootcat, '-no-emul-boot', '-boot-load-size', '4', '-boot-info-table', '-o', dest, '.']):
        #print stderr, line
        # mkisofs uses stderr for progress
        if not stderr:
            continue
        match = re.match(ur'\s+?(\d+.\d+)\%.*', line)

        if not match:
            continue

        percent = float(match.group(1))

        progress_data = {'name':dest, 'percent': percent}

        Tool.SIGNAL_TOOL_PROGRESS(mkisofs, progress_data, message="Creating filesystem...")



    Tool.SIGNAL_TOOL_START(mkisofs, message="Finished creating filesystem...")
